<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2021/1/9  11:16
 */
namespace App\Services\Api;
use App\Models\UserRankExp;
use App\Models\User;
use App\Models\UserRank;


class UserRankExpServices{

    public function add_user_rank_exp($data){

        //$userObj = User::where('id',$data['user_id'])->select(['id','user_rank_id','user_rank_level'])->first();

        $res = UserRankExp::insert($data);

        //$user_rank = $this->get_user_rank($userObj->id);

//        if(!empty($user_rank)){
//            //更改级别
//            $userObj->user_rank_id = $user_rank['id'];
//            $userObj->user_rank_level = $user_rank['level'];
//            $userObj->save();
//        }

        return $res;

    }

    public function get_user_rank($user_id){
        $exp_value = UserRankExp::where('id', $user_id)->sum('exp_value');

        return self::get_level($exp_value);
    }

    /**
     * 获取等级信息
     * @param int $exp_value  用户有多少积分
     * @param array $level    查询多少等级
     */
    public static function get_level($exp_value=0)
    {
        $result = [
            'id'=>0,
            'level'=>0,
        ];

        if($exp_value>0) {

            $user_rank = UserRank::select(['id', 'level', 'rank_min'])->orderBy('rank_min', 'desc')->get()->toArray();

            foreach ($user_rank as $value) {
                if ($exp_value > $value['rank_min']) {
                    $result['id'] = $value['id'];
                    $result['level'] = $value['level'];
                    break;
                }
            }

        }else{

            //等於0的時候看該等級最低級

            $user_rank = UserRank::where('rank_min',0)->select(['id', 'level'])->first();

            if(!empty($user_rank)){
                $result['id'] = $user_rank->id;
                $result['level'] = $user_rank->level;
            }

        }

        return $result;
    }

}
